#!/usr/bin/env python
#coding:utf-8
import urllib2,re

class Astro:
    """Class to get up-to-date astro information from sina astro"""

    def __init__( self, query ):
        """initializing the astro and the date received"""
        self.__astrolist={'白羊座':'0','白羊':'0','aries':'0',
                          '金牛座':'1','金牛':'1','taurus':'1',
                          '双子座':'2','双子':'2','gemini':'2',
                          '巨蟹座':'3','巨蟹':'3','cancer':'3',
                          '狮子座':'4','狮子':'4','leo':'4',
                          '处女座':'5','处女':'5','virgo':'5',
                          '天秤座':'6','天秤':'6','libra':'6',
                          '天蝎座':'7','天蝎':'7','scorpio':'7',
                          '射手座':'8','射手':'8','sagittarius':'8',
                          '魔羯座':'9','魔羯':'9','capricorn':'9',
                          '水瓶座':'10','水瓶':'10','aquarius':'10',
                          '双鱼座':'11','双鱼':'11','pisces':'11'}
        self.__date={'今日':'','今天':'','today':'',
                     '明日':'_1','明天':'_1','tomorrow':'_1'}
        self.__res_header=''
        self.setUrl(query)


    def setUrl ( self,query ):
        """function to set the url"""
        if(len(query)>=2 and (query[1] in self.__astrolist)):
            if(len(query)==3 and (query[2] in self.__date)):
                self.__url='http://astro.sina.com.cn/pc/west/frame0_%s%s.html'%(self.__astrolist[query[1]],self.__date[query[2]])
                self.__res_header='['+query[1]+query[2]+'运程] '
            elif(len(query)==2):
                self.__url='http://astro.sina.com.cn/pc/west/frame0_%s.html'%(self.__astrolist[query[1]])
                self.__res_header='['+query[1]+'今日运程] '
            else:
                self.__url='http://astro.sina.com.cn/pc/west/frame'
        else:
            self.__url='http://astro.sina.com.cn/pc/west/frame'



    def getPage( self ):
        """function to get the content of the web page.return the string page content"""
        url=self.__url
        page_content=''
        retry=4
        for tim in range(retry):
            try:
                page = urllib2.urlopen(url)
                page_content = page.read()
                page.close()
                break
            except:
                pass
        return page_content


    def getDayLucky(self , page_content):
        """function to get the info we needed form the pages.return a list respons"""
        match=[]
        if(cmp(self.__date,"week")<>0):
            regex=r'<div class="lotconts">(.*?)</div>'
            data1=re.findall( regex, page_content )
            if(data1<>[]):
                data1[0]=data1[0].replace("<br />","")
                data1[0]=unicode(data1[0].decode('gbk').encode('utf-8'),"utf-8")
                res=[]
                if len(data1[0])>=110:
                    c=len(data1[0])/110
                    sign=0
                    for i in range(c):
                        res.append(self.__res_header+data1[0][sign:sign+110].encode('utf-8'))
                        sign+=110
                    if (len(data1[0])%110<>0):
                        res.append(self.__res_header+data1[0][sign:len(data1[0])].encode('utf-8'))
                    res.reverse()
                else:
                    res=data1
                    res[0]=self.__res_header+res[0].encode('utf-8')
            else:       
                return []
            regex=r'<div class="tab">(.*?)</div>'
            data2=re.findall( regex, page_content )
            star='''<img src="http://image2.sina.com.cn/ast/2007index/tmp/star_php/star.gif" width="18" height="18" />'''
            if(len(data2)>=9):
                reponse=self.__res_header+"综合: "
                reponse=reponse+str(len(re.findall(star,data2[0])))+"星 "
                reponse=reponse+"爱情: "
                reponse=reponse+str(len(re.findall(star,data2[1])))+"星 "
                reponse=reponse+"工作状况: "
                reponse=reponse+str(len(re.findall(star,data2[2])))+"星 "
                reponse=reponse+"理财投资: "
                reponse=reponse+str(len(re.findall(star,data2[3])))+"星 "
                reponse=reponse+"健康指数: "
                reponse=reponse+re.findall("<p>(.*?)</p>",data2[4])[0].decode('gbk').encode('utf-8')+" "
                reponse=reponse+"商谈指数: "
                reponse=reponse+re.findall("<p>(.*?)</p>",data2[5])[0].decode('gbk').encode('utf-8')+" "
                reponse=reponse+"幸运颜色: "
                reponse=reponse+re.findall("<p>(.*?)</p>",data2[6])[0].decode('gbk').encode('utf-8')+" "
                reponse=reponse+"幸运数字: "
                reponse=reponse+re.findall("<p>(.*?)</p>",data2[7])[0].decode('gbk').encode('utf-8')+" "
                reponse=reponse+"速配星座: "
                reponse=reponse+re.findall("<p>(.*?)</p>",data2[8])[0].decode('gbk').encode('utf-8')+" "
                res=res+[reponse]
                return res                   
            else:
                return []
        else:
            res=[]
            regex=r'<li class="notes">(.*?)</div>'
            data1=re.findall( regex, page_content )
            if(data1<>[]):
                res=data1
            else:
                return []
            
            

    def getAstro( self ):
        """function to get the up-to-day info about astro.return a list reply"""
        page_content=self.getPage().replace("\n","") # Get the content of the result web page from sina astro
        match=self.getDayLucky(page_content)        
        if( match==[] ):
            return ["Oops,查询连接超时或输入有误，请检查输入格式，稍后再试"]
        respon=match
        return respon
  

            
